#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include "Common.hpp"

class InetAddr
{
private:
    void PortNet2Host() // 网络转成主机
    {
        _port = ::ntohs(_net_addr.sin_port);
    }
    void IpNet2Host()
    {
        char npbuffer[64];
        const char *ip = ::inet_ntop(AF_INET, &_net_addr.sin_addr.s_addr, npbuffer, sizeof(npbuffer));
        (void)ip;
    }

public:
    uint16_t GetPort()
    {
        return _port;
    }
    std::string GetIp()
    {
        return _ip;
    }

    std::string ID()const
    {
        return _ip + ": " + std::to_string(_port);
    }

    struct sockaddr *GetSockaddr_In()
    {
        return CONV(&_net_addr);
    }

    socklen_t LenSockaddr_in()
    {
        return sizeof(_net_addr);
    }

    bool operator == (const InetAddr& add)
    {
        return (add._ip == _ip)&&(add._port == _port);//两个都相等才返回true
    }

    InetAddr()
    {
    }
    InetAddr(uint16_t port) : _port(port), _ip("")
    {
        _net_addr.sin_family = AF_INET;
        _net_addr.sin_port = htons(_port);
        _net_addr.sin_addr.s_addr = INADDR_ANY;
    }
    InetAddr(const struct sockaddr_in &addr) : _net_addr(addr)
    {
        PortNet2Host();
        IpNet2Host();
    }
    InetAddr(const InetAddr &addrr)
        : _net_addr(addrr._net_addr), _ip(addrr._ip), _port(addrr._port)
    {
    }
    ~InetAddr()
    {
    }

private:
    struct sockaddr_in _net_addr;
    std::string _ip;
    uint16_t _port;
};